#include "DeviceMessageBuilder.h"
#include "DeviceMessageParserV2.h"
#include <iostream>
#include <cassert>
#include <chrono>
#include <thread>
#include <windows.h>

using namespace DeviceCommons;
using namespace std::chrono;

/// <summary>
/// DeviceCommons C++简化版演示
/// 专注于V2协议的功能展示和性能测试
/// </summary>
class DeviceCommonsDemo {
public:
   
    static void runAllDemos() {
        std::cout << "============================================" << std::endl;
        std::cout << "     DeviceCommons C++简化版演示" << std::endl;
        std::cout << "     仅支持V2协议，确保与C#版本兼容" << std::endl;
        std::cout << "============================================" << std::endl;
        
        basicUsageDemo();
        dataTypesDemo();
        performanceDemo();
        asyncDemo();
        compatibilityDemo();
        
        std::cout << "\n所有演示完成！" << std::endl;
    }

private:
    /// <summary>
    /// 基础用法演示
    /// </summary>
    static void basicUsageDemo() {
        std::cout << "\n=== 1. 基础用法演示 ===" << std::endl;
        
        try {
            // 创建简单的V2协议消息
            auto builder = DeviceMessageBuilder::create()
                .withMainDevice("IoTGateway", 0x01)
                .addChild("TempSensor", 0x10)
                .addChild("HumiditySensor", 0x20);
            
            // 添加读数数据
            std::vector<State> mainStates = {
                State::makeString(1, "Online"),
                State::makeFloat32(2, 25.6f),
                State::makeBool(3, true)
            };
            builder.addReading(1000, mainStates);
            
            auto hex = builder.buildHex();
            std::cout << "V2协议消息: " << hex << std::endl;
            std::cout << "消息长度: " << hex.length() / 2 << " 字节" << std::endl;
            
            // 验证协议头部
            auto bytes = builder.buildBytes();
            assert(bytes[0] == 0xC0 && bytes[1] == 0xBF && bytes[2] == 0x02);
            std::cout << "[PASS] V2协议头部验证成功" << std::endl;
            
            // 测试解析器功能
            auto parsed = DeviceMessageParserV2::parseFromHex(hex);
            std::cout << "[PASS] 消息解析成功" << std::endl;
            printParsedMessage(parsed);
            
        } catch (const std::exception& e) {
            std::cerr << "基础用法演示失败: " << e.what() << std::endl;
        }
    }
    
    /// <summary>
    /// 所有数据类型演示
    /// </summary>
    static void dataTypesDemo() {
        std::cout << "\n=== 2. 数据类型兼容性演示 ===" << std::endl;
        
        try {
            auto builder = DeviceMessageBuilder::create()
                .withMainDevice("MultiTypeDevice", 0x01);
            
            // 演示所有支持的StateValueType类型
            std::vector<State> allTypes = {
                State::makeFloat32(1, 3.14159f),           // StateValueType::Float32 = 1
                State::makeInt32(2, -12345),               // StateValueType::Int32 = 2
                State::makeString(3, "Hello World"),       // StateValueType::String = 3
                State::makeBool(4, true),                  // StateValueType::Bool = 4
                State::makeUInt16(6, 65535),               // StateValueType::UInt16 = 6
                State::makeInt16(7, -32768),               // StateValueType::Int16 = 7
                State::makeTimestamp(8, 1640995200000ULL), // StateValueType::Timestamp = 8
                State::makeBinary(9, {0x01, 0x02, 0x03, 0xFF}), // StateValueType::Binary = 9
                State::makeDouble(10, 2.718281828459045)   // StateValueType::Double = 10
            };
            
            builder.addReading(0, allTypes);
            
            auto message = builder.buildHex();
            std::cout << "包含所有数据类型的消息: " << std::endl;
            std::cout << message << std::endl;
            
            // 验证每种数据类型
            for (const auto& state : allTypes) {
                std::cout << "状态类型 " << static_cast<int>(state.type)
                          << " (SID=" << static_cast<int>(state.sid) << ") "
                          << "数据长度: " << state.value.size() << " 字节" << std::endl;
            }
            
            std::cout << "[PASS] 所有数据类型兼容性验证成功" << std::endl;
            
        } catch (const std::exception& e) {
            std::cerr << "数据类型演示失败: " << e.what() << std::endl;
        }
    }
    
    /// <summary>
    /// 性能测试演示
    /// </summary>
    static void performanceDemo() {
        std::cout << "\n=== 3. 性能测试演示 ===" << std::endl;
        
        try {
            const int iterations = 1000;
            
            // 创建复杂消息用于性能测试
            auto builder = DeviceMessageBuilder::create()
                .withMainDevice("PerformanceTestDevice", 0x05);
            
            // 添加多个子设备
            for (int i = 0; i < 10; ++i) {
                builder.addChild("ChildDevice" + std::to_string(i), 0x06);
            }
            
            // 添加多个读数
            for (int i = 0; i < 5; ++i) {
                std::vector<State> states = {
                    State::makeString(1, "Performance Test Data " + std::to_string(i)),
                    State::makeFloat32(2, static_cast<float>(i * 1.5)),
                    State::makeInt32(3, i * 1000),
                    State::makeBool(4, i % 2 == 0)
                };
                builder.addReading(static_cast<int16_t>(i * 100), states);
            }
            
            // 性能测试
            auto start = high_resolution_clock::now();
            
            for (int i = 0; i < iterations; ++i) {
                auto result = builder.buildHex();
                // 避免编译器优化掉未使用的结果
                volatile auto length = result.length();
            }
            
            auto end = high_resolution_clock::now();
            auto duration = duration_cast<microseconds>(end - start);
            
            std::cout << "性能测试结果:" << std::endl;
            std::cout << "  迭代次数: " << iterations << std::endl;
            std::cout << "  总耗时: " << duration.count() << " 微秒" << std::endl;
            std::cout << "  平均耗时: " << duration.count() / iterations << " 微秒/次" << std::endl;
            std::cout << "  吞吐量: " << (iterations * 1000000.0) / duration.count() << " 消息/秒" << std::endl;
            
            std::cout << "[PASS] 性能测试完成" << std::endl;
            
        } catch (const std::exception& e) {
            std::cerr << "性能测试失败: " << e.what() << std::endl;
        }
    }
    
    /// <summary>
    /// 异步功能演示
    /// </summary>
    static void asyncDemo() {
        std::cout << "\n=== 4. 异步功能演示 ===" << std::endl;
        
        try {
            auto builder = DeviceMessageBuilder::create()
                .withMainDevice("AsyncTestDevice", 0x01);
            
            std::vector<State> states = {
                State::makeString(1, "异步测试数据"),
                State::makeFloat32(2, 42.0f)
            };
            builder.addReading(100, states);
            
            std::cout << "启动异步构建..." << std::endl;
            auto start = high_resolution_clock::now();
            
            // 启动异步操作
            auto bytesAsync = builder.buildBytesAsync();
            auto hexAsync = builder.buildHexAsync();
            
            std::cout << "异步操作已启动，正在执行其他工作..." << std::endl;
            
            // 模拟其他工作
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
            
            // 获取异步结果
            auto bytes = bytesAsync.get();
            auto hex = hexAsync.get();
            
            auto end = high_resolution_clock::now();
            auto duration = duration_cast<milliseconds>(end - start);
            
            std::cout << "异步操作完成:" << std::endl;
            std::cout << "  字节数组长度: " << bytes.size() << std::endl;
            std::cout << "  十六进制长度: " << hex.length() << std::endl;
            std::cout << "  总耗时: " << duration.count() << " 毫秒" << std::endl;
            
            // 验证结果一致性
            auto syncHex = builder.buildHex();
            assert(hex == syncHex);
            std::cout << "[PASS] 异步结果与同步结果一致" << std::endl;
            
        } catch (const std::exception& e) {
            std::cerr << "异步演示失败: " << e.what() << std::endl;
        }
    }
    
    /// <summary>
    /// C#兼容性验证演示
    /// </summary>
    static void compatibilityDemo() {
        std::cout << "\n=== 5. C#兼容性验证演示 ===" << std::endl;
        
        try {
            // 创建与C#版本API风格兼容的消息
            auto builder = DeviceMessageBuilder::create()
                .withHeader(CRCType::CRC16, TimeStampFormat::MS, HeaderValueType::Standard)
                .withMainDevice("CompatibilityTest", 1)
                .withChildDevice("ChildDevice1", 148)
                .withChildDevice("ChildDevice2", 148);
            
            // 添加各种类型的状态数据
            std::vector<State> states = {
                State::makeString(1, "兼容性测试"),
                State::makeFloat32(2, 25.5f),
                State::makeInt32(3, 12345),
                State::makeBool(4, true)
            };
            builder.addReading(100, states);
            
            auto message = builder.buildHex();
            auto bytes = builder.buildBytes();
            
            std::cout << "兼容性测试消息: " << message << std::endl;
            
            // 验证关键格式
            std::cout << "协议格式验证:" << std::endl;
            std::cout << "  魔数字: 0x" << std::hex << static_cast<int>(bytes[0]) << static_cast<int>(bytes[1]) << std::dec;
            std::cout << " (期望: 0xC0BF)" << std::endl;
            
            std::cout << "  协议版本: 0x" << std::hex << static_cast<int>(bytes[2]) << std::dec;
            std::cout << " (期望: 0x02)" << std::endl;
            
            std::cout << "  设备总数: " << static_cast<int>(bytes[4]);
            std::cout << " (期望: 3 = 1主设备 + 2子设备)" << std::endl;
            
            // 验证格式正确性
            assert(bytes[0] == 0xC0 && bytes[1] == 0xBF);  // 魔数字
            assert(bytes[2] == 0x02);                       // V2协议
            assert(bytes[4] == 3);                          // 设备总数
            
            std::cout << "[PASS] 所有兼容性验证通过" << std::endl;
            std::cout << "[PASS] 可与C#版本进行数据交换" << std::endl;
            
        } catch (const std::exception& e) {
            std::cerr << "兼容性验证失败: " << e.what() << std::endl;
        }
    }
};

int main() {
    SetConsoleOutputCP(65001);
    SetConsoleCP(65001);
    try {
        DeviceCommonsDemo::runAllDemos();
        return 0;
    } catch (const std::exception& e) {
        std::cerr << "演示程序异常: " << e.what() << std::endl;
        return 1;
    }
}